<?php
define("DB_SERVERNAME", "localhost");
define("DB_USERNAME", "root");
define("DB_PASSWORD", "1234");
define("DB_DATABASE", "test");

class db
{
    protected static function conn()
    {
        $conn = new mysqli(DB_SERVERNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
        if ($conn->connect_error) {
            die("连接失败: " . $conn->connect_error);
        }
        return $conn;
    }

    public static function createDb()
    {
        $conn = new mysqli(DB_SERVERNAME, DB_USERNAME, DB_PASSWORD);
        if ($conn->connect_error) {
            die("连接失败: " . $conn->connect_error);
        }
        $sql = "CREATE DATABASE " . DB_DATABASE;
        if ($conn->query($sql) === TRUE) {
            echo "<br/>Database created successfully";
        } else {
            echo "<br/>Error creating database: " . $conn->error . "<br/>This sql：" . $sql;
        }
        $conn->close();
    }

    public static function createDt()
    {
        $conn = self::conn();
        if ($conn->connect_error) {
            die("连接失败: " . $conn->connect_error);
        }
        $sql = "CREATE TABLE `user`(
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `name` VARCHAR(30) NOT NULL,
        `password` VARCHAR(30) NOT NULL
    );";
        $sql .= "CREATE TABLE `examinee`(
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `testnumber` VARCHAR(30) NOT NULL,
        `idnumber` VARCHAR(30) NOT NULL,
        `name` VARCHAR(30) NOT NULL,
        `password` VARCHAR(30) NOT NULL
    );";
        $sql .= "CREATE TABLE `subject`(
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `name` VARCHAR(30) NOT NULL,
        `startime` DATETIME NOT NULL,
        `endtime` DATETIME NOT NULL
    );";
        $sql .= "CREATE TABLE `file`(
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `filelocation` VARCHAR(200) NOT NULL,
        `addtime` DATETIME NOT NULL,
        `examinee_id` INT(6) UNSIGNED NOT NULL,
        `subject_id` INT(6) UNSIGNED NOT NULL,
        FOREIGN KEY(`examinee_id`) REFERENCES `examinee`(id),
        FOREIGN KEY(`subject_id`) REFERENCES `subject`(id)
    );";

        if ($conn->multi_query($sql) === TRUE) {
            echo "<br/>Table created successfully";
        } else {
            echo "<br/>Error creating datatable: " . $conn->error . "<br/>This sql：" . $sql;
        }
        $conn->close();
    }

    public static function _array($sql)
    {
        $conn =self::conn();
        $result = $conn->query($sql);
        $dataarr = array();
        while ($row = mysqli_fetch_assoc($result)) {
            $dataarr[] = $row;
        }
        $conn->close();
        return $dataarr;
    }

    public static function _bool($sql)
    {
        $conn = self::conn();
        $result = $conn->query($sql);
        $conn->close();
        return $result;
    }
}

// db::createDb();
// db::createDt();
